<?php


namespace app\user\controller;


use EasyWeChat\Factory;
use EasyWeChat\Kernel\Exceptions\InvalidArgumentException;
use EasyWeChat\Kernel\Exceptions\InvalidConfigException;
use think\Controller;
use think\facade\Config;
use think\facade\Request;

class Vip extends Controller
{

    protected $middleware = [
        'app\http\middleware\checkTTUserToken::class' => ['except' => ['payCallBack']],
    ];


    public function join()
    {
        $user_id = Request::param('user_id');

        $user = \app\user\model\User::get($user_id);

        $config = Config::get("miniprogram.wechat_pay");

        $payment = Factory::payment($config);
        $jssdk = $payment->jssdk;

        $result = $payment->order->unify([
            'body' => '会员费用',
            'out_trade_no' => time(),
            'total_fee' => 100,
            'notify_url' => 'https://dzs.ilanchong.cn/user/vip/payCallBack', // 支付结果通知网址，如果不设置则会使用配置里的默认地址
            'trade_type' => 'JSAPI',        // 请对应换成你的支付方式对应的值类型
            "attach" => json_encode([
                'user_id'=>$user_id
            ]),        //附加参数，会在回调中原样返回
            'openid' => $user->wx_openid,
        ]);

        $config = $jssdk->bridgeConfig($result['prepay_id'], false); // 返回数组

        $this->result($config, 200);

    }

    public function payCallBack()
    {
        $data = file_get_contents('php://input');
        $arr = $this->XmlToArr($data);

        setLog('callback', json_encode($arr));

        // 判断返回状态
        if ($arr['return_code'] == 'SUCCESS' || $arr['result_code'] == 'SUCCESS') {
            $out_trade_no=$arr['out_trade_no'];

            //查询订单是否真的成功了
            $config = Config::get("miniprogram.wechat_pay");

            $app = Factory::payment($config);
            try {
                $res = $app->order->queryByOutTradeNumber($out_trade_no);
                setLog('开通会员，支付成功', json_encode($res));
                $attach=json_decode($res['attach']);
                \app\user\logic\User::JoinVip($attach->user_id);
//                setLog('user_id', $attach->user_id);
                echo '<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>';//给微信正常相应（如果没有正常相应微信会根据自己的机制多次请求）

            } catch (InvalidArgumentException $e) {
            } catch (InvalidConfigException $e) {

            }
        }
    }


//数组转Xml
    public function ArrToXml($arr)
    {
        if (!is_array($arr) || count($arr) == 0) return '';

        $xml = "<xml>";
        foreach ($arr as $key => $val) {
            if (is_numeric($val)) {
                $xml .= "<" . $key . ">" . $val . "</" . $key . ">";
            } else {
                $xml .= "<" . $key . "><![CDATA[" . $val . "]]></" . $key . ">";
            }
        }
        $xml .= "</xml>";
        return $xml;
    }

    //Xml转数组
    public function XmlToArr($xml)
    {
        if ($xml == '') return '';
        libxml_disable_entity_loader(true);
        $arr = json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
        return $arr;
    }

}
